package com.yeskery.nut.application.tomcat;

import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.websocket.JavaxWebSocketLoader;
import com.yeskery.nut.websocket.WebSocketConfiguration;
import org.apache.catalina.Context;
import org.apache.tomcat.websocket.server.Constants;
import org.apache.tomcat.websocket.server.WsContextListener;

import javax.websocket.server.ServerContainer;
import java.util.Collection;

/**
 * Tomcat WebSocket加载器
 * @author sprout
 * @version 1.0
 * 2023-04-16 01:30
 */
public class JavaxTomcatWebSocketLoader extends JavaxWebSocketLoader implements TomcatWebSocketLoader {

    /**
     * 构建Tomcat WebSocket加载器
     * @param applicationContext 应用上下文
     */
    JavaxTomcatWebSocketLoader(ApplicationContext applicationContext) {
        super(applicationContext);
    }

    /**
     * 添加WebSocket
     * @param context Tomcat Server 上下文对象
     */
    @Override
    public void addWsContextListener(Context context) {
        context.addApplicationListener(WsContextListener.class.getName());
    }

    /**
     * 注册WebSocket服务端点
     * @param context Tomcat Server 上下文对象
     * @param webSocketConfigurations WebSocket配置对象集合
     */
    @Override
    public void registerEndpoints(Context context, Collection<WebSocketConfiguration> webSocketConfigurations) {
        ServerContainer serverContainer = (ServerContainer) context.getServletContext().getAttribute(
                Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
        registerEndpoints(serverContainer, webSocketConfigurations);
    }
}
